import React, { useState, useEffect } from 'react';
import { useNavigate, useLocation } from 'react-router-dom';
import { Toast } from 'antd-mobile';
import axios from 'axios';
import styles from './Register.module.css';
import  {http,host,port} from '../utils/host'
const Register: React.FC = () => {
    const navigate = useNavigate();
    const location = useLocation();
    const [formData, setFormData] = useState({
        username: '',
        studentId: '',
        password: '',
        confirmPassword: ''
    });
    const [selectedSchool, setSelectedSchool] = useState<any>(null);
    const [agreedToPrivacy, setAgreedToPrivacy] = useState(false);
    const [isLoading, setIsLoading] = useState(false);

    // 从URL参数获取学校信息
    useEffect(() => {
        const searchParams = new URLSearchParams(location.search);
        const schoolId = searchParams.get('schoolId');
        const schoolName = searchParams.get('schoolName');
        
        if (schoolId && schoolName) {
            // 获取学校详细信息
            getSchoolInfo(schoolId);
        } else {
            // 如果没有学校信息，跳转到学校选择页面
            Toast.show({
                content: '请先选择学校',
                position: 'center',
            });
            navigate('/chooseschool');
        }
    }, [location, navigate]);

    // 获取学校详细信息
    const getSchoolInfo = async (schoolId: string) => {
        try {
            const res = await axios.get(`${http}${host}${port}/school/${schoolId}`);
            if (res.data.code === 200) {
                setSelectedSchool(res.data.data);
            }
        } catch (error) {
            console.error('获取学校信息失败:', error);
            Toast.show({
                content: '获取学校信息失败',
                position: 'center',
            });
            navigate('/chooseschool');
        }
    };

    // 验证用户名
    const validateUsername = (username: string) => {
        return username.length >= 3 && username.length <= 10;
    };

    // 验证学号格式（根据选择的学校）
    const validateStudentId = (studentId: string) => {
        if (!selectedSchool || !selectedSchool.studentIdRule) {
            return studentId.length >= 8 && studentId.length <= 12;
        }

        const { minLength, maxLength, pattern } = selectedSchool.studentIdRule;
        
        if (studentId.length < minLength || studentId.length > maxLength) {
            return false;
        }

        if (pattern && !new RegExp(pattern).test(studentId)) {
            return false;
        }

        return true;
    };

    // 验证密码强度
    const validatePassword = (password: string) => {
        return password.length >= 6;
    };

    // 注册处理
    const handleRegister = async () => {
        // 表单验证
        if (!formData.username.trim()) {
            Toast.show({
                content: '请输入用户名',
                position: 'center',
            });
            return;
        }

        if (!validateUsername(formData.username)) {
            Toast.show({
                content: '用户名长度应为3-20位',
                position: 'center',
            });
            return;
        }

        if (!selectedSchool) {
            Toast.show({
                content: '请先选择学校',
                position: 'center',
            });
            return;
        }

        if (!validateStudentId(formData.studentId)) {
            const rule = selectedSchool.studentIdRule;
            if (rule) {
                Toast.show({
                    content: rule.description || `学号长度应为${rule.minLength}-${rule.maxLength}位`,
                    position: 'center',
                });
            } else {
                Toast.show({
                    content: '请输入正确的学号',
                    position: 'center',
                });
            }
            return;
        }

        if (!validatePassword(formData.password)) {
            Toast.show({
                content: '密码长度至少6位',
                position: 'center',
            });
            return;
        }

        if (formData.password !== formData.confirmPassword) {
            Toast.show({
                content: '两次输入的密码不一致',
                position: 'center',
            });
            return;
        }

        if (!agreedToPrivacy) {
            Toast.show({
                content: '请先同意用户隐私政策',
                position: 'center',
            });
            return;
        }

        try {
            setIsLoading(true);
            
            const response = await axios.post(`${http}${host}${port}/register`, {
                username: formData.username,
                studentId: formData.studentId,
                schoolId: selectedSchool._id,
                password: formData.password
            });

            if (response.data.code === 200) {
                Toast.show({
                    content: '注册成功',
                    position: 'center',
                });
                navigate('/login');
            } else {
                Toast.show({
                    content: response.data.message || '注册失败',
                    position: 'center',
                });
            }

        } catch (error: any) {
            console.error('注册错误详情:', {
                message: error.message,
                response: error.response?.data,
                status: error.response?.status,
                statusText: error.response?.statusText
            });
            
            let errorMessage = '注册失败，请重试';
            if (error.code === 'ERR_NETWORK') {
                errorMessage = '网络连接失败，请检查后端服务是否启动';
            } else if (error.response?.data?.message) {
                errorMessage = error.response.data.message;
            } else if (error.response?.status === 404) {
                errorMessage = '注册接口不存在，请检查后端服务';
            } else if (error.response?.status === 500) {
                errorMessage = '服务器内部错误';
            }
            
            Toast.show({
                content: errorMessage,
                position: 'center',
            });
        } finally {
            setIsLoading(false);
        }
    };

    // 处理输入变化
    const handleInputChange = (field: string, value: string) => {
        setFormData(prev => ({
            ...prev,
            [field]: value
        }));
    };


    // 返回学校选择页面
    const handleBackToSchoolSelect = () => {
        navigate('/chooseschool');
    };
    
    return (
        <div className={styles['register-container']}>
            {/* 背景装饰元素 */}
            <div className={styles['background-decoration']} />
            <div className={styles['background-decoration-2']} />

            {/* 主要内容区域 */}
            <div className={styles['main-content']}>
                {/* 标题区域 */}
                <div className={styles['title-section']}>
                    <h1 className={styles['register-title']}>加入校园生活</h1>
                    <p className={styles['subtitle']}>创建你的校园账号</p>
                    {selectedSchool && (
                        <div className={styles['selected-school']}>
                            <span>已选择：{selectedSchool.name}</span>
                            <button 
                                className={styles['change-school-btn']}
                                onClick={handleBackToSchoolSelect}
                            >
                                更换学校
                            </button>
                        </div>
                    )}
                </div>

                {/* 表单区域 */}
                <div className={styles['form-section']}>
                    {/* 用户名输入 */}
                    <div className={styles['input-group']}>
                        <input
                            type="text"
                            className={styles['input-field']}
                            placeholder="请输入用户名（3-10位）"
                            value={formData.username}
                            onChange={(e) => handleInputChange('username', e.target.value)}
                            maxLength={20}
                        />
                    </div>

                    {/* 学号输入 */}
                    <div className={styles['input-group']}>
                        <input
                            type="text"
                            className={styles['input-field']}
                            placeholder={selectedSchool?.studentIdRule?.description || "请输入学号"}
                            value={formData.studentId}
                            onChange={(e) => handleInputChange('studentId', e.target.value.toUpperCase())}
                            maxLength={selectedSchool?.studentIdRule?.maxLength || 10}
                        />
                    </div>

                    {/* 密码输入 */}
                    <div className={styles['input-group']}>
                        <input
                            type="password"
                            className={styles['input-field']}
                            placeholder="请输入密码（至少6位）"
                            value={formData.password}
                            onChange={(e) => handleInputChange('password', e.target.value)}
                        />
                    </div>

                    {/* 确认密码输入 */}
                    <div className={styles['input-group']}>
                        <input
                            type="password"
                            className={styles['input-field']}
                            placeholder="请确认密码"
                            value={formData.confirmPassword}
                            onChange={(e) => handleInputChange('confirmPassword', e.target.value)}
                        />
                    </div>

                    {/* 隐私政策 */}
                    <div className={styles['privacy-section']}>
                        <input
                            type="checkbox"
                            className={styles['privacy-checkbox']}
                            checked={agreedToPrivacy}
                            onChange={(e) => setAgreedToPrivacy(e.target.checked)}
                        />
                        <span>我已阅读并同意</span>
                        <a href="#" className={styles['privacy-link']}>
                            《用户隐私政策》
                        </a>
                    </div>

                    {/* 注册按钮 */}
                    <button
                        className={styles['register-button']}
                        onClick={handleRegister}
                        disabled={isLoading}
                    >
                        {isLoading ? '注册中...' : '立即注册'}
                    </button>

                    {/* 登录链接 */}
                    <div className={styles['login-link-section']}>
                        <span>已有账号？</span>
                        <a
                            href="#"
                            className={styles['login-link']}
                            onClick={(e) => {
                                e.preventDefault();
                                navigate('/login');
                            }}
                        >
                            立即登录
                        </a>
                    </div>
                </div>
            </div>
        </div>
    );
};

export default Register;